package com.example.controller;

import com.example.service.WordToPdfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@RestController
@RequestMapping("/api")
public class WordToPdfController {

    @Autowired
    private WordToPdfService wordToPdfService;

    @PostMapping("/word-to-pdf")
    public ResponseEntity<?> convertWordToPdf(@RequestParam("file") MultipartFile file) {
        try {
            // 获取桌面路径
//            String desktopPath = System.getProperty("user.home") + "/Desktop";
//
//            String outputPdfPath = desktopPath + "/output.pdf";  // 输出 PDF 文件保存到桌面

            String outputPdfPath = System.getProperty("user.home") + "/Desktop/output_" + System.currentTimeMillis() + ".pdf";

            // 读取上传的 Word 文件
            InputStream wordInputStream = file.getInputStream();

            // 调用服务方法转换为 PDF
            wordToPdfService.convertWordToPdf(wordInputStream, outputPdfPath);

            // 将生成的 PDF 文件返回为 ResponseEntity 以供下载
            File pdfFile = new File(outputPdfPath);
            InputStream pdfInputStream = new FileInputStream(pdfFile);
            byte[] pdfBytes = pdfInputStream.readAllBytes();

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output.pdf");

            return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件转换失败");
        }
    }

}
